﻿Imports sonicERPDAL
Imports sonicERPinfo
Imports System.IO
Imports System.Data.SqlTypes
Imports System.Web.HttpContext
Imports System.Xml
Imports System.Security
Imports System.Security.Principal
Imports System.Data.SqlClient
Imports System.Xml.Serialization
Imports System.Xml.XPath
Imports System.Web.Mvc
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Web.UI.Page
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.Control
Imports System.Reflection
Imports System.Collections.Specialized








Public Class Util

    Dim dal As New fornecedorDAL
    Dim entidade As New fornercedorInfo
    Dim dados As New UsuarioDAL
    Dim entidad As New UsuarioInfo

    ''' <summary>
    ''' procedimento para exportal excel
    ''' comando select para setar a tabela
    ''' </summary>
    ''' <param name="nomearquivo">nome do arquivo excel </param>
    ''' <param name="tabela"></param>
    ''' <remarks></remarks>


    Public Sub exportarexcel(ByVal nomearquivo As String, ByVal tabela As DataView)

        Dim context As HttpContext = HttpContext.Current
        context.Response.Clear()
        For Each coluna As DataColumn In tabela.Table.Columns
            context.Response.Write(coluna.ColumnName + ";")
        Next
        context.Response.Write(Environment.NewLine)
        For Each row As DataRowView In tabela
            For index As Integer = 0 To tabela.Table.Columns.Count - 1
                context.Response.Write(row(index).ToString.Replace(";", String.Empty) & ";")
            Next
            context.Response.Write(Environment.NewLine)
        Next
        context.Response.ContentType = "text/csv"
        context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + nomearquivo + ".csv")
        context.Response.End()











    End Sub

    Private dadosArray() As String = {"111.111.111-11", "222.222.222-22", "333.333.333-33", "444.444.444-44", _
                                              "555.555.555-55", "666.666.666-66", "777.777.777-77", "888.888.888-88", "999.999.999-99"}

    Private Const msgErro As String = "Dados Inválidos"
    Private bValida As Boolean
    Private sCPF As String
    Private sCNPJ As String

    Private Function ValidaCPF(ByVal CPF As String) As Boolean
        Dim i, x, n1, n2 As Integer
        CPF = CPF.Trim
        For i = 0 To dadosArray.Length - 1
            If CPF.Length <> 14 Or dadosArray(i).Equals(CPF) Then
                Return False
            End If
        Next
        'remove a maskara
        CPF = CPF.Substring(0, 3) + CPF.Substring(4, 3) + CPF.Substring(8, 3) + CPF.Substring(12)
        For x = 0 To 1
            n1 = 0
            For i = 0 To 8 + x
                n1 = n1 + Val(CPF.Substring(i, 1)) * (10 + x - i)
            Next
            n2 = 11 - (n1 - (Int(n1 / 11) * 11))
            If n2 = 10 Or n2 = 11 Then n2 = 0
            If n2 <> Val(CPF.Substring(9 + x, 1)) Then
                Return False
            End If
        Next
        Return True

    End Function
    Private Function ValidaCNPJ(ByVal CNPJ As String) As Boolean
        Dim i As Integer
        Dim valida As Boolean
        CNPJ = CNPJ.Trim
        For i = 0 To dadosArray.Length - 1
            If CNPJ.Length <> 18 Or dadosArray(i).Equals(CNPJ) Then
                Return False
            End If
        Next
        'removE a maskara
        CNPJ = CNPJ.Substring(0, 2) + CNPJ.Substring(3, 3) + CNPJ.Substring(7, 3) + CNPJ.Substring(11, 4) + CNPJ.Substring(16)
        valida = efetivaValidacao(CNPJ)
        If valida Then
            ValidaCNPJ = True
        Else
            ValidaCNPJ = False
        End If
    End Function


    Private Function efetivaValidacao(ByVal cnpj As String)
        Dim Numero(13) As Integer
        Dim soma As Integer
        Dim i As Integer
        Dim resultado1 As Integer
        Dim resultado2 As Integer
        For i = 0 To Numero.Length - 1
            Numero(i) = CInt(cnpj.Substring(i, 1))
        Next
        soma = Numero(0) * 5 + Numero(1) * 4 + Numero(2) * 3 + Numero(3) * 2 + Numero(4) * 9 + Numero(5) * 8 + Numero(6) * 7 + _
                   Numero(7) * 6 + Numero(8) * 5 + Numero(9) * 4 + Numero(10) * 3 + Numero(11) * 2
        soma = soma - (11 * (Int(soma / 11)))
        If soma = 0 Or soma = 1 Then
            resultado1 = 0
        Else
            resultado1 = 11 - soma
        End If
        If resultado1 = Numero(12) Then
            soma = Numero(0) * 6 + Numero(1) * 5 + Numero(2) * 4 + Numero(3) * 3 + Numero(4) * 2 + Numero(5) * 9 + Numero(6) * 8 + _
                         Numero(7) * 7 + Numero(8) * 6 + Numero(9) * 5 + Numero(10) * 4 + Numero(11) * 3 + Numero(12) * 2
            soma = soma - (11 * (Int(soma / 11)))
            If soma = 0 Or soma = 1 Then
                resultado2 = 0
            Else
                resultado2 = 11 - soma
            End If
            If resultado2 = Numero(13) Then
                Return True
            Else
                Return False
            End If
        Else
            Return False
        End If
    End Function

    ''' <summary>
    ''' procedimentro exportar para xml
    ''' </summary>
    ''' <param name="nomearquivo">nome do arquivo xml gerado</param>
    ''' <param name="tabela">passar o select para dataview</param>
    ''' <remarks></remarks>

    Public Sub exportarxml(ByVal nomearquivo As String, ByVal tabela As DataView)
        Dim dt As DataTable = tabela.ToTable

        Dim sb As New StringBuilder
        sb.Append("<" + dt.TableName + ">")

        For Each row As DataRow In dt.Rows
            sb.Append("<item>")

            For index As Integer = 0 To dt.Columns.Count - 1
                sb.Append("<" + dt.Columns(index).ColumnName + ">" + row(index).ToString() + "<" + dt.Columns(index).ColumnName + ">")
            Next
            sb.Append("</item>")
        Next
        sb.Append("</" + dt.TableName + "/>")
        HttpContext.Current.Response.ClearHeaders()

        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + nomearquivo + ".xml")
        HttpContext.Current.Response.AppendHeader("Content-Length", sb.Length.ToString())
        HttpContext.Current.Response.ContentType = "text/xml"
        HttpContext.Current.Response.Write(sb.ToString())
        HttpContext.Current.Response.End()


    End Sub

    Public Function getusuarios(ByVal lista As List(Of String)) As IList(Of String)
        Dim principal As IPrincipal
        principal = HttpContext.Current.User
        entidad.nome = principal.Identity.Name
        Dim dt As DataTable = dados.getusuario(entidad)

        For Each dados As DataRow In dt.Rows
            For index = 0 To dt.Columns.Count - 1
                lista.Add(dados.Item(index).ToString())
            Next
        Next
        Return lista

    End Function
    ''' <summary>
    ''' Validar a  Pagina verificar se a Pagina Pode Ser Acessada
    ''' </summary>
    ''' <param name="indice">Retorna o indice da pagina que esta acessando no menu o indice se encontra na tabela menu </param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function validarpagina(ByVal indice As Integer) As Boolean
        Try
            Dim visivel As Boolean

            Dim dal As New menuDAL
            Dim entidade As New sonicERPinfo.Menu
            Dim Principal As IPrincipal
            Principal = HttpContext.Current.User
            entidade.usuario = Principal.Identity.Name
            If Principal.Identity.IsAuthenticated Then

                Dim dv As DataView = dal.getmenu(entidade)
                Dim dt As DataTable = dv.ToTable()

                visivel = Convert.ToBoolean(dt.Rows(indice).Item(0).ToString())
            End If
            Return visivel
        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try
    End Function

    Public Sub excel()
        entidade.dtinicio = SqlDateTime.MinValue
        entidade.dt_fim = SqlDateTime.MaxValue
        entidade.nomefornecedor = Convert.ToString(DBNull.Value)
        entidade.tipofornecedor = Convert.ToString(DBNull.Value)

        Dim nome = "teste"
        Dim tabela As DataView = dal.getfornecedor(entidade)
        exportarexcel(nome, tabela)

    End Sub

    Public Sub print()
        Dim cn As New conexao
        Dim cCOn As New SqlConnection(cn.conexao)
        Dim dbRead As SqlDataReader
        Dim cCommand As SqlCommand
        Dim cSQL As New StringBuilder
        Dim strTable As New StringBuilder

        cSQL.AppendLine("SELECT id,nome FROM CLIENTE")

        cCOn.Open()
        cCommand = New SqlCommand(cSQL.ToString(), cCOn)
        dbRead = cCommand.ExecuteReader


        While dbRead.Read()

            strTable.AppendLine("<table width=""100%"" height=""100%"" border=""3"" bordercolordark=""#000000"" bordercolorlight=""#000000"" bordercolor=""#000000""><tr><td>")
            strTable.AppendLine("<br><br><br> ")
            strTable.AppendLine("<center><table width=""840"" height=""650"" >")
            strTable.AppendLine("<tr>")
            strTable.AppendLine("<td colspan=""3"" align=""center""><span class=""rec_sbot"">A Sociedade Brasileira de Ortopedia e Traumatologia</span><br>")
            strTable.AppendLine("<span class=""rec_norma""l"">e sua Comissão de Educação Continuada e Pesquisa</span></td>")
            strTable.AppendLine("</tr><tr>")
            strTable.AppendLine("<td colspan=""3"" class=""rec_normal"">após a avaliação dos créditos obtidos pelo Membro Titular, Dr" + dbRead("id").ToString() + ".<br></td>")
            strTable.AppendLine("</tr><tr>")
            strTable.AppendLine("<td colspan=""3"" class=""rec_nome_titulo_ano"">" + dbRead("nome").ToString() + "<br></td>")
            strTable.AppendLine("</tr><tr>")
            strTable.AppendLine("</table>")
            strTable.AppendLine("</center> ")
            strTable.AppendLine("</td></tr></table>")
            strTable.AppendLine("<P CLASS=""QuebraAqui"">")
        End While
        cCOn.Close()
        dbRead.Close()
        HttpContext.Current.Response.Write(strTable.ToString())

    End Sub


    Public Sub imprimir(ByVal dt As DataTable)
        Dim st As New StringBuilder
        st.Append("<style type=""text/css"">" +
           ".table, th, td {" +
   "border: 1px solid black;}" +
         "  .table {" +
   " border-collapse:collapse;}" +
          " .table, th, td {" +
   " border: 1px solid black;} " +
         "  .table{ " +
   "width:775px; }" +
         "  .th {" +
   " height:50px; }" +
   "        .td {" +
   "height:50px;" +
   " vertical-align:bottom; }" +
         "  .td {" +
   "padding:15px; } " +
      "     .table, td, th {" +
   "border:1px solid Blue; }" +
          " .th {" +
   " background-color:Blue;" +
   "color:white; " +
   " font-size:inherit; }" +
    ".style4 {width: 866px;} " +
    " .cabecalho{" +
   " height: 182px; width: 866px;}" +
   ".style4{width: 866px;}" +
    " .cabecalho{" +
    " height: 182px; width: 994px;}" +
        "  </style>" +
       " <div id=""teste""> <table id=""tabela"" class=""cabecalho"">" +
            " <tr> " +
              "   <td>" +
"<img  alt=""Smiley face""  id=""Image1"" src=""../img/sonic-2.gif"" style=""margin-top: 0px; width:152px; height:192px;"" />" +
          "    </td>" +
         "  <td class=""style4"">" +
         "    <img  alt=""Smiley face"" id=""Image2"" style=""margin-top: 0px; width:826px; height:193px;"" src=""../img/imagem.PNG""/>" +
            "  </td>" +
       " </tr>" +
   " </table>")

        st.AppendLine("<center><table class=""table"" >")
        st.AppendLine("<tr class=""th"">")
        For Each coluna As DataColumn In dt.Columns
            st.AppendLine("<td class=""td"">" + coluna.ColumnName.ToString() + "&nbsp;</td>")
        Next
        st.AppendLine("</tr>")
        For Each row As DataRow In dt.Rows
            st.AppendLine(" <tr>")
            For index = 0 To dt.Columns.Count - 1
                st.AppendLine("<td>" + row.Item(index).ToString() + "&nbsp;</td>")
            Next
            st.AppendLine(" </tr>")
            st.AppendLine(" <br />")
        Next
        st.AppendLine(" </table></center></div>")
        HttpContext.Current.Response.Write(st.ToString())


    End Sub

    Public Sub xml()

        'entidade.dtinicio = SqlDateTime.MinValue
        'entidade.dt_fim = SqlDateTime.MaxValue
        'entidade.nomefornecedor = Convert.ToString(DBNull.Value)
        'entidade.tipofornecedor = Convert.ToString(DBNull.Value)

        Dim nome = "teste"
        'Dim tabela As DataView = dal.getfornecedor(entidade)
        Dim dal As New sonicERPDAL.ClienteDAL
        Dim entidade As New sonicERPinfo.Tabelainfo
        entidade.cliente.nomecliente = Convert.ToString(DBNull.Value)
        entidade.cliente.tipocliente = Convert.ToString(DBNull.Value)
        entidade.cliente.dtinicio = Convert.ToDateTime("01/01/2011")
        entidade.cliente.dt_fim = Convert.ToDateTime("01/12/2012")
        Dim dv As DataView = dal.getlista(entidade)

        exportarxml(nome, dv)

    End Sub

    Public Sub idade()
        Dim dtnascimento As Date = "07/06/1983"
        Dim ano As Integer = dtnascimento.Year
        Dim hoje As Integer = Now.Date.Year
        Dim idade As Integer = hoje - ano
        Dim dthoje As Date = Now.Date.AddDays(-ano)

    End Sub

    Public Function gerarxml(ByVal obj As Object, ByVal nometabela As String, ByVal tipocomando As String)
        Try
            Using ms As New MemoryStream



                Dim xml As New XmlTextWriter(ms, Encoding.GetEncoding("UTF-16"))
                xml.WriteStartDocument()
                xml.WriteStartElement(nometabela + "s")

                xml.Formatting = Formatting.Indented
                xml.WriteElementString("TipoComando", tipocomando)
                For Each coluna As PropertyInfo In obj.GetType.GetProperties

                    xml.Formatting = Formatting.Indented
                    xml.WriteElementString(coluna.Name, CType(coluna.GetValue(obj, Nothing), String))

                Next
                xml.WriteEndElement()

                xml.WriteEndDocument()
                xml.Flush()
                ms.Position = 0
                Dim sr As New StreamReader(ms)

                Dim s As String = sr.ReadToEnd()
                ms.Flush()
                ms.Close()
                xml.Close()
                sr.Close()

                Return s
            End Using
        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try
    End Function

    Public Function gerarxml(ByVal obj As Object)

        Try

            Dim x As New XmlSerializer(obj.GetType())
            Dim manespace As New XmlSerializerNamespaces
            Dim setting As New XmlWriterSettings
            setting.Encoding = New UnicodeEncoding(False, False)
            setting.Indent = False
            setting.OmitXmlDeclaration = False
            Using textWriter As New StringWriter

                Dim xml As XmlWriter = XmlWriter.Create(textWriter, setting)

                manespace.Add(String.Empty, String.Empty)

                x.Serialize(xml, obj, manespace)

                xml.Flush()
                xml.Close()

                Return textWriter.ToString()
            End Using


        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try
    End Function
    Public Function gerarxml(ByVal obj As Object, ByVal nometabela As String, ByVal tipocomando As String, ByVal dv As DataView)
        Try



            Dim list As New List(Of ListItem)

            For Each coluna As PropertyInfo In obj.GetType.GetProperties
                list.Add(New ListItem(coluna.Name, coluna.GetValue(obj, Nothing)))
            Next
            For Each item As DataRow In dv.Table.Rows
                For index = 0 To dv.Table.Columns.Count - 1
                    list.Add(New ListItem(dv.Table.Columns(index).ColumnName, item(index).ToString()))
                Next
            Next
            Using ms As New MemoryStream
                Dim xml As New XmlTextWriter(ms, Encoding.GetEncoding("UTF-16"))
                xml.WriteStartDocument()
                xml.WriteStartElement(nometabela + "s")
                xml.Formatting = Formatting.Indented
                xml.WriteElementString("TipoComando", tipocomando)

                For index = 0 To list.Count - 1
                    xml.Formatting = Formatting.Indented
                    xml.WriteElementString(list(index).Text, list(index).Value)

                Next
                xml.WriteEndElement()

                xml.WriteEndDocument()
                xml.Flush()
                ms.Position = 0
                Dim sr As New StreamReader(ms)

                Dim s As String = sr.ReadToEnd()
                ms.Flush()
                ms.Close()
                xml.Close()
                sr.Close()

                Return s
            End Using
        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try
    End Function
    Public Function BuscaCep(ByVal cep As String) As CepInfo
        Dim ds As DataSet
        Dim resultado As String
        Dim ceps As New CepInfo
        Dim ht As System.Collections.Hashtable
        Try
            ds = New DataSet()
            ds.ReadXml("http://cep.republicavirtual.com.br/web_cep.php?cep=" + cep.Replace("-", "").Trim() + "&formato=xml")
            If Not IsNothing(ds) Then
                If (ds.Tables(0).Rows.Count > 0) Then
                    resultado = ds.Tables(0).Rows(0).Item("resultado").ToString()
                    ht = New Hashtable
                    Select Case resultado
                        Case ("1")
                            ht.Add("UF", ds.Tables(0).Rows(0).Item("uf").ToString().Trim())
                            ht.Add("cidade", ds.Tables(0).Rows(0).Item("cidade").ToString().Trim())
                            ht.Add("bairro", ds.Tables(0).Rows(0).Item("bairro").ToString().Trim())
                            ht.Add("tipologradouro", ds.Tables(0).Rows(0).Item("tipo_logradouro").ToString().Trim())
                            ht.Add("logradouro", ds.Tables(0).Rows(0).Item("logradouro").ToString().Trim())
                            ht.Add("tipo", 1)
                            ceps.logradouro = ht("logradouro").ToString
                            ceps.cidade = ht("cidade").ToString
                            ceps.estado = ht("UF").ToString
                            ceps.bairro = ht("bairro").ToString
                        Case ("2")
                            ht.Add("UF", ds.Tables(0).Rows(0).Item("uf").ToString().Trim())
                            ht.Add("cidade", ds.Tables(0).Rows(0).Item("cidade").ToString().Trim())
                            ht.Add("tipo", 2)
                        Case Else

                    End Select
                End If
            End If
            Return ceps
        Catch ex As Exception
            Throw New Exception("Falha ao Buscar o Cep" & vbCrLf & ex.ToString)

        End Try
    End Function

    Private _teste As Integer = 10
    Public ReadOnly Property teste() As Integer
        Get
            Return _teste
        End Get

    End Property

    Public Sub teste1()
        Dim i As Integer
        i = teste


    End Sub
#Region "Caixa de Mensagens"

    ''' <summary>
    ''' Buscas the controle.
    ''' </summary>
    ''' <param name="control">The control.</param>
    ''' <param name="type">The type.</param>
    ''' <returns></returns>
    Public Shared Function BuscaControle(ByVal control As Control, ByVal type As Type) As Control
        If control.[GetType]() = type Then
            Return control
        End If
        For Each c As Control In control.Controls
            Dim controlChild As Control = BuscaControle(c, type)
            If controlChild IsNot Nothing Then
                Return controlChild
            End If
        Next
        Return Nothing
    End Function

    ''' <summary>
    ''' Exibe uma caixa de mensagem através de uma determinada página
    ''' </summary>
    ''' <param name="pagina">Página onde a caixa de mensagem será exibida</param>
    ''' <param name="mensagem">A mensagem que será exibida</param>
    Public Shared Sub Alerta(ByVal pagina As Page, ByVal mensagem As String)
        Dim updatePanel As Control = BuscaControle(pagina, GetType(UpdatePanel))
        Dim alert As String = String.Format("$(function(){{Alerta(""{0}"");}});", MensagemHtml(mensagem))
        If updatePanel Is Nothing Then
            pagina.ClientScript.RegisterStartupScript(pagina.[GetType](), "MessageBox", alert, True)
        Else
            ScriptManager.RegisterClientScriptBlock(updatePanel, updatePanel.[GetType](), "MessageBox", alert, True)
        End If
    End Sub

    ''' <summary>
    ''' Exibe uma caixa de mensagem através de uma determinada página
    ''' </summary>
    ''' <param name="pagina">Página onde a caixa de mensagem será exibida</param>
    ''' <param name="mensagem">A mensagem que será exibida</param>
    ''' <param name="titulo">Titulo do alerta</param>
    Public Shared Sub Alerta(ByVal pagina As Page, ByVal mensagem As String, ByVal titulo As String)
        Dim updatePanel As Control = BuscaControle(pagina, GetType(UpdatePanel))
        Dim alert As String = String.Format("$(function(){{Alerta(""{0}"",""{1}"");}});", MensagemHtml(mensagem), titulo)
        If updatePanel Is Nothing Then
            pagina.ClientScript.RegisterStartupScript(pagina.[GetType](), "MessageBox", alert, True)
        Else
            ScriptManager.RegisterClientScriptBlock(updatePanel, updatePanel.[GetType](), "MessageBox", alert, True)
        End If
    End Sub

    ''' <summary>
    ''' Exibe uma caixa de mensagem através de uma determinada página, e após a leitura redireciona para outra página
    ''' </summary>
    ''' <param name="pagina">Página onde a caixa de mensagem será exibida</param>
    ''' <param name="mensagem">A mensagem que será exibida</param>
    ''' <param name="titulo">Titulo do alerta</param>
    ''' <param name="novaPagina">Página para onde a aplicação será redirecionada</param>
    Public Shared Sub Alerta(ByVal pagina As Page, ByVal mensagem As String, ByVal titulo As String, ByVal novaPagina As String)
        Dim updatePanel As Control = BuscaControle(pagina, GetType(UpdatePanel))
        Dim alert As String = String.Format("$(function(){{Alerta(""{0}"",""{1}"",""{2}"");}});", MensagemHtml(mensagem), titulo, novaPagina)
        If updatePanel Is Nothing Then
            pagina.ClientScript.RegisterStartupScript(pagina.[GetType](), "MessageBox", alert, True)
        Else
            ScriptManager.RegisterClientScriptBlock(updatePanel, updatePanel.[GetType](), "MessageBox", alert, True)
        End If
    End Sub

    ''' <summary>
    ''' Exibe uma caixa de mensagem através de uma determinada página, e após a leitura redireciona para outra página
    ''' </summary>
    ''' <param name="pagina">Página onde a caixa de mensagem será exibida</param>
    ''' <param name="mensagem">A mensagem que será exibida</param>
    ''' <param name="titulo">Titulo do alerta</param>
    ''' <param name="novaPagina">Página para onde a aplicação será redirecionada</param>
    ''' <param name="width">Tamanho do alerta</param>
    Public Shared Sub Alerta(ByVal pagina As Page, ByVal mensagem As String, ByVal titulo As String, ByVal novaPagina As String, ByVal width As String)
        Dim updatePanel As Control = BuscaControle(pagina, GetType(UpdatePanel))
        Dim alert As String = String.Format("$(function(){{Alerta(""{0}"",""{1}"",""{2}"",{3});}});", MensagemHtml(mensagem), titulo, novaPagina, width)
        If updatePanel Is Nothing Then
            pagina.ClientScript.RegisterStartupScript(pagina.[GetType](), "MessageBox", alert, True)
        Else
            ScriptManager.RegisterClientScriptBlock(updatePanel, updatePanel.[GetType](), "MessageBox", alert, True)
        End If
    End Sub

    ''' <summary>
    ''' Exibe uma caixa de mensagem através de uma determinada página, e após a leitura redireciona para outra página
    ''' </summary>
    ''' <param name="pagina">Página onde a caixa de mensagem será exibida</param>
    ''' <param name="mensagem">A mensagem que será exibida</param>
    ''' <param name="titulo">Titulo do alerta</param>
    ''' <param name="novaPagina">Página para onde a aplicação será redirecionada</param>
    ''' <param name="width">Tamanho do alerta</param>
    ''' <param name="width">Javascript a ser executada quando clicar em OK</param>
    Public Shared Sub Alerta(ByVal pagina As Page, ByVal mensagem As String, ByVal titulo As String, ByVal novaPagina As String, ByVal width As String, ByVal script As String)
        Dim updatePanel As Control = BuscaControle(pagina, GetType(UpdatePanel))
        Dim alert As String = String.Format("$(function(){{Alerta(""{0}"",""{1}"",""{2}"",{3},function(){{{4}}});}});", MensagemHtml(mensagem), titulo, novaPagina, width, script)
        If updatePanel Is Nothing Then
            pagina.ClientScript.RegisterStartupScript(pagina.[GetType](), "MessageBox", alert, True)
        Else
            ScriptManager.RegisterClientScriptBlock(updatePanel, updatePanel.[GetType](), "MessageBox", alert, True)
        End If
    End Sub

    Private Shared Function MensagemHtml(ByVal mensagem As String) As String
        Return mensagem.Replace(vbCr, "").Replace(vbTab, "").Replace("""", "&quot;").Replace(vbLf, "<br />")
    End Function
#End Region
End Class
